<?php
class MessagesController extends AppController {

	var $name = 'Messages';
	var $helpers = array('Time', 'Lemur');

	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->deny('index');
	}


	function index() {
		$data = false;
		$uid = $this->Auth->user('id');
		
		if ($uid) {
			$this->paginate = $this->Message->paginateConditions('to', $uid);
			$data['messages'] = $this->paginate('Message');
		}

		if ($data) {
			$this->set($data);
		}
	}

	function replieds() {
		$data = false;
		$uid = $this->Auth->user('id');

		if ($uid) {
			$this->paginate = $this->Message->paginateConditions('from', $uid);
			$data['messages'] = $this->paginate('Message');
		}

		if ($data) {
#pr ($data);
			$this->set($data);
		}

	}

	function read($id = null) {
		$data = false;
		$uid = $this->Auth->user('id');

		if ($uid) {
			$c = array('to_id'=>$uid, 'id'=>$id);
			$data['messages'] = $this->Message->find('all', array('conditions'=>$c, 'recursive'=>2));

			if (!empty($data['messages'])) {
				$this->Message->changeStatus($id, 1);
			}


			if (isset($this->data['Message']) && $data['messages']) {
				if (!empty($data['messages'][0]['Message']['from_id'])) {
					$this->data['Message']['from_id']	=  $uid;
					$this->data['Message']['to_id']		=  $data['messages'][0]['Message']['from_id'];
					if ($this->Message->sendMessage($this->data)) {
						$this->Session->setFlash('Ответ отправлен');
						$this->redirect('/messages');
					}
				}
			}
		}

		if ($data) {
#pr ($data);
			$this->set($data);
		}
	}

	function delete($id = null) {
		$id = intval($id);
		$uid = $this->Auth->user('id');
		if ($id && $uid) {

			if ($this->Message->deleteMessage($id, $uid)) {
				$this->Session->setFlash('Сообщене удалено');
			} else {
				$this->Session->setFlash('Сообщене не удалено');
			}

			$this->redirect('/messages');
		}
	}

	function counter($status = 0) {
		$uid = $this->Auth->user('id');
		if ($uid) {
			$c = array('to_id'=>$uid, 'status'=>$status);
			return $this->Message->find('count', array('conditions'=>$c));
		}
	}


}
?>
